<?php
/**
 * session 重写类使用Redis
 * User: 林辉
 * Date: 2017/7/1
 * Time: 15:09
 */

namespace Common\Lib;


class SessionRedis
{
    /**
     * Session有效时间
     */
    protected $lifeTime = '';

    /**
     * session保存的数据库名
     */
    protected $sessionTable = '';

    /**
     * 数据库句柄
     */
    protected $hander = array();

    /**
     * @var null|\Redis
     */
    private $redis = null;

    private $config = [
        'host'=>'127.0.0.1',
        'port'=>'6379',
        'expire'=>'3600',
        'auth'=>'',
    ];

    /**
     * 打开Session
     * @access public
     * @param string $savePath
     * @param mixed $sessName
     * @return bool
     */
    public function open($savePath, $sessName)
    {
        $this->config = array_merge($this->config, (array)C("REDIS"));
        $this->redis = new \Redis();
        $this->redis->connect($this->config['host'], $this->config['port']);
        if($this->config['auth']) {
            $this->redis->auth($this->config['auth']);
        }
        return true;
    }

    /**
     * 关闭Session
     * @access public
     */
    public function close()
    {
        $this->redis->close();
        return true;
    }

    /**
     * 读取Session
     * @access public
     * @param string $sessID
     * @return bool|string
     */
    public function read($sessID)
    {
        return $this->redis->get("SESSION:{$_SERVER['HTTP_HOST']}{$sessID}");
    }

    /**
     * 写入Session
     * @access public
     * @param string $sessID
     * @param String $sessData
     * @return bool
     */
    public function write($sessID, $sessData)
    {
        return $this->redis->setex("SESSION:{$_SERVER['HTTP_HOST']}{$sessID}", $this->config['expire'], $sessData);
    }

    /**
     * 删除Session
     * @access public
     * @param string $sessID
     * @return int
     */
    public function destroy($sessID)
    {
        return $this->redis->del("SESSION:{$_SERVER['HTTP_HOST']}{$sessID}");
    }

    /**
     * Session 垃圾回收
     * @access public
     * @param string $sessMaxLifeTime
     * @return bool
     */
    public function gc($sessMaxLifeTime)
    {
        return true;
    }
}